package com.ningxun.rms.service.userservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ningxun.rms.common.core.domain.entity.SysUser;
import com.ningxun.rms.common.core.domain.model.LoginUser;
import com.ningxun.rms.common.utils.uuid.UUID;
import com.ningxun.rms.service.userservice.IBaseWechatUserService;
import org.apache.commons.lang3.ObjectUtils;
import com.ningxun.rms.domain.basewechatuser.BaseWechatUser;
import com.ningxun.rms.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;

@Service
public class WechatUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IBaseWechatUserService baseWechatUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  验证用户身份查询openid 将openid放入userName中
        BaseWechatUser baseWechatUser = baseWechatUserService.queryBaseWechatUserByopenid(username);
        if(ObjectUtils.isEmpty(baseWechatUser )){
            BaseWechatUser newUser = new BaseWechatUser();
            newUser.setCreateTime(DateUtils.getNowDate());
            newUser.setOpenId(username);
            String uuid = "微信用户_" + UUID.randomUUID();
            uuid = uuid.substring(0 , 25);
            newUser.setName(uuid);
            newUser.setGender(0L);
            baseWechatUserService.save(newUser);
        }
        LambdaQueryWrapper<BaseWechatUser> wrapper = new LambdaQueryWrapper<BaseWechatUser>()
                .select(BaseWechatUser::getUserId)
                .eq(BaseWechatUser::getOpenId , username);
        BaseWechatUser userid = baseWechatUserService.getOne(wrapper);
        //  如果不为空，就让表中数据提交
        SysUser user = new SysUser();
        user.setUserName(username);
        return new LoginUser(userid.getUserId(), 0L, user, new HashSet<>());
    }
}
